package com.aeye.mbr.common.template.engine;

import com.aeye.mbr.common.exception.TalkeduException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.StringTemplateResolver;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * Thymeleaf模板引擎
 */
public class ThymeleafTemplateEngine implements TemplateEngine{


    private static Logger log = LoggerFactory.getLogger(ThymeleafTemplateEngine.class);


    private SpringTemplateEngine mEngine;


    public ThymeleafTemplateEngine() {
        this.mEngine = new SpringTemplateEngine();
        StringTemplateResolver resolver = new StringTemplateResolver();
        resolver.setTemplateMode(TemplateMode.TEXT);
        resolver.setOrder(9);
        mEngine = new SpringTemplateEngine();
        mEngine.setTemplateResolver(resolver);

    }

    @Override
    public String merge(String template, Map<String, Object> params) {
        try {
            String result = mergeTemplate(template, params);
            return result;
        } catch (Exception e) {
            log.error("merge出现异常!",e);
        }
        return template;
    }


    public String mergeTemplate(String template, Map<String, Object> params) {
        Context ctx = new Context(Locale.CHINESE);
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                ctx.setVariable(key, params.get(key));
            }
        }
        try {
            String result = mEngine.process(template, ctx);
            log.debug("merge结果:\n转换之前:\n" + template + "\n转换之后:\n" + result);
            return result;
        } catch (Exception e) {
            log.error("模板语法错误:\n" + template + "\n", e);
            throw new TalkeduException("merge模板出现异常!");
        }
    }


    @Override
    public boolean checkTemplateSyntax(String template) {
        try {
            mergeTemplate(template, new HashMap<String, Object>());
            return true;
        } catch (Exception e) {

        }
        return false;
    }
}
